package net.esj.basic.core.view.interceptor;

import java.util.Locale;
import java.util.Set;

import javax.validation.ConstraintViolation;

import net.esj.basic.core.engine.support.MelonSupporter;
import net.esj.basic.core.engine.support.validator.ValidateAware;
import net.esj.basic.core.engine.support.validator.exception.MelonValidateException;
import net.esj.basic.core.engine.support.validator.exception.ValidateMessage;
import net.esj.basic.core.view.filter.I18NFilter;
import net.esj.basic.utils.i18n.LocaleUtils;
import net.esj.basic.validate.defaults.DefaultJSR303Validator;
import net.esj.basic.validate.defaults.DefaultJSR303Validator.ValidateEntry;

import org.springframework.context.MessageSource;
import org.springframework.util.StringUtils;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class ValidatorInterceptor extends AbstractInterceptor{

	private DefaultJSR303Validator validationBean;
	
	public static final String VALIDATOR_MESSAGE_KEY_POSTFIX = ".error";
	
	@Override
	public void init() {
		validationBean = (DefaultJSR303Validator) MelonSupporter.getValidator();
		super.init();
	}

	@Override
	public String intercept(ActionInvocation arg0) throws Exception {
		if(arg0.getAction() instanceof ValidateAware){
			Set<ConstraintViolation<Object>> set = validationBean.validate(arg0.getAction());
			if(set.size()>0){
				ValidateMessage vm = new ValidateMessage(set.size());
				for(ConstraintViolation<Object> tmp:set){
					if(arg0.getAction() instanceof MessageSource){
						String message = tmp.getMessage();
						if(!StringUtils.hasText(message)){
							message = arg0.getAction().getClass().getName()+"_"+tmp.getPropertyPath()+VALIDATOR_MESSAGE_KEY_POSTFIX;
						}
						String msg = ((MessageSource)arg0.getAction()).getMessage(message,null, message,LocaleUtils.findLocale());
						vm.add(new ValidateEntry(tmp.getPropertyPath().toString(),msg));
					}else{
						vm.add(DefaultJSR303Validator.decipherValidateMessageInI18N(tmp, (Locale)arg0.getInvocationContext().getSession().get(I18NFilter.STRUTS_I18N_KEY)));
					}
				}
				throw new MelonValidateException("效验不通过，请核查原因", vm);
			}
		}
		return arg0.invoke();
	}

}
